<template>
	<view class="page">
		<!-- #ifdef H5 -->
			<topVue title="AI声音训练" :isBack="true" rightIcon="server-fill"></topVue>
		<!-- #endif -->

		<view class="main-content">
			<scroll-view class="content" scroll-y>
				<view class="h2">上传录制的声音</view>
				<view class="tip">上传时长必须保持在5-10秒，文件格式支持mp3、wav，确保录制的声音清晰无杂音，以便获得最佳训练效果。</view>
				<view class="uploadBtn margin30" @click="chooseAudio()">点我上传音频</view>

				<view class="inpVue padding-column30" v-if="audioName && url">
					<view class="label">当前上传音频</view>
					<view class="sudioVue flex-between align-center">
						<audio :src="url" :name="audioName" controls style="width: 580rpx;"></audio>
						<u-icon name="close" color="#81868e" size="30" @click="audioName = ''; url = ''"></u-icon>
					</view>
				</view>

				<!-- 设置声音名称 -->
				<view class="inpVue padding-column30">
					<view class="label">设置声音名称</view>
					<input type="text" placeholder="请设置声音名称" v-model="name"/>
				</view>

				<!-- 选择声音性别 -->
				<view class="inpVue">
					<view class="label">选择声音性别</view>
					<view class="radioVue flex">
						<view class="radio flex align-center" @click="radio=1">
							<image src="../../static/radio0.png" style="width: 48rpx; height: 48rpx;" v-if="radio===0"></image>
							<image src="../../static/radio1.png" style="width: 48rpx; height: 48rpx;" v-if="radio===1"></image>
							<view class="sex">男</view>
						</view>
						<view class="radio flex align-center" @click="radio=0">
							<image src="../../static/radio0.png" style="width: 48rpx; height: 48rpx;" v-if="radio===1"></image>
							<image src="../../static/radio1.png" style="width: 48rpx; height: 48rpx;" v-if="radio===0"></image>
							<view class="sex" style="border: none;">女</view>
						</view>
					</view>
				</view>

				<!-- 开始训练 -->
				<view class="tipVue flex align-center margin20">
					<u-checkbox v-model="checked" active-color="#6917ED" label-size="24" ><text style="color: #888; line-height: 1;">公开训练后声音，可获得100积分用于合成视频</text></u-checkbox>
				</view>

				<view class="startBtn margin20" @click="startFun()">开始训练</view>
				<view class="flex-between align-center margin20">
					<text style="color: #888;">剩余训练额度：{{ availableQuota }}次</text>
					<text style="color: #6AA1F8; text-decoration: underline;" @click="$tools.route('../mine/voice')">购买额度</text>
				</view>

				<!-- 我的声音列表 -->
				<view class="flex-between align-center margin30">
					<view class="h2">我的声音列表</view>
					<text style="color: #6AA1F8; text-decoration: underline;" @click="$tools.route('../mine/voice')">声音管理</text>
				</view>
				<u-subsection :list="tabs" :current="current" :button-color="buttonColor" active-color="#fff" bg-color="#F3F4F6" @change="getList"></u-subsection>

				<scroll-view scroll-y style="width: 100%; height:300rpx; padding-top: 15rpx;">
					<view class="w100 flex-column align-center padding-column20 absolute-auto" v-if="list.length===0">
						<image src="../../static/empty.png" style="width: 196rpx; height: 196rpx;"></image>
						<text style="color: #81868e;">当前列表为空</text>
					</view>
					<u-gap height="2"></u-gap>
					<view class="tabItem flex align-center" v-for="(item, index) in list" :key="index">
						<audio :src="item.url" :name="`${item.name}-${item.sex}`" controls></audio>
					</view>
				</scroll-view>

				<!-- 训练中的声音 -->
				<template v-if="trainingList.length>0">
					<view class="h2">训练中的声音</view>
					<view style="color: #92B3D0; line-height: 1;">训练中的声音进度，请耐心等待</view>
					<view class="progressItem flex align-center" v-for="(item, index) in trainingList" :key="item.taskId">
						<view class="name line-1">{{ item.name }}</view>
						<u-line-progress
							active-color="#3B82F6"
							inactive-color="#F3F4F6"
							:percent="item.progress"
							:striped="true"
							:striped-active="true"
							height="36"
							>
						</u-line-progress>
					</view>
				</template>
			</scroll-view>
		</view>
	</view>
</template>

<script>
	import baseUrl from "@/common/url.js"
	export default {
		data(){
			return{
				radio: 1,
				checked: false,
				tabs: [{name: "全部"}, {name:"男"}, {name: "女"}],
				current: 0,
				audioUrl: "",
				url: "",
				audioName: "",
				name: "",
				voiceState:"",
				availableQuota: 0,
				list: [],
				trainingList: [],
				innerAudioContext: null,
				buttonColor: "linear-gradient(to right, #49DC83, #3B83F4)",
			}
		},

		async onLoad() {
			await this.getSoundQuota()
			await this.getList()
			await this.getTrainingList()
		},

		methods: {
			// 获取用户声音训练额度
			async getSoundQuota(){
				const res = await this.$request("/shuziren/soundQuota", {}, "GET")
				if(res.code===200) this.availableQuota = res.data.availableQuota
			},

			// 获取用户已完成训练的声音列表
			async getList(e){
				let choose = e ? e : this.current
				const res = await this.$request("/shuziren/soundTrain/done", {
					sex:this.tabs[choose].name
				}, "GET")
				if(res.code===200) this.list = res.data
			},

			//获取用户正在训练的声音
			async getTrainingList(){
				const res = await this.$request("/shuziren/soundTrain/training", {}, "GET")
				if(res.code===200) {
					this.trainingList = res.data
					let pages = getCurrentPages();
					let curRoute = pages[pages.length - 1].route //获取当前页面路由
					if(curRoute==="pages/videoMaker/voice") {
						setTimeout(()=>{
							if(this.trainingList.length>0) this.getTrainingList()
						}, 3000)
					}
				}
			},

			// 开始训练声音
			async startFun(){
				if(this.availableQuota===0) return this.$u.toast("额度不足，请购买额度")
				if(!this.name) return this.$u.toast("请设置声音名称")
				if(!this.url) return this.$u.toast("请上传声音")
				uni.showLoading()
				const res = await this.$request("/shuziren/soundTrain/start", {
					name: this.name,
					sex: this.radio===0 ? "女" : "男",
					isPublic: this.checked,
					url: this.url
				}, "POST", "application/json")
				if(res.code===200) {
					uni.hideLoading()
					this.$u.toast("训练开始，请等稍等")
					this.name = ""
					this.url = ""
					this.radio = 1
					this.availableQuota-=1
					this.getTrainingList()
					this.getList()
				}else{
					uni.hideLoading()
					this.$u.toast(res.msg)
				}
			},

			// 选择声音
			chooseAudio(){
				let that = this
				uni.chooseFile({
					count: 1,
					extension: [".wav", ".mp3", ".m4a", ".amr"],
					success(res) {
						let fileName = res.tempFiles[0].name
						if(!fileName.endsWith(".wav") && !fileName.endsWith(".mp3") && !fileName.endsWith("m4a") && !fileName.endsWith("amr")) return that.$u.toast("请选择音频文件")
						console.log(res)
						let tempFilePaths = res.tempFilePaths[0]
						uni.showLoading()
						uni.uploadFile({
							url: baseUrl.url + "/aiet-file-center/file",
							filePath: tempFilePaths,
							name: "file",
							formData: {
								"path": "shuziren/audio"
							},
							success(uploadRes) {
								uni.hideLoading()
								let data = JSON.parse(uploadRes.data)
								console.log(data)
								if(data.code===200) {
									that.audioName = data.data.fileUrl.split("/")[data.data.fileUrl.split("/").length-1]
                  that.recordingDuration(data.data.fileUrl)
								}else{
									that.$u.toast(data.msg)
								}
							},
							fail(uploadError){
								console.log(uploadError)
								uni.hideLoading()
								that.$u.toast("上传失败")
							}
						})
					},
					fail(e){
						console.log(e)
					}
				})
			},
      async recordingDuration(url) {
        let that = this
        const res = await this.$request("/shuziren/soundTrain/getDuration", {
          prompt_wav: url
        }, "POST","application/json")
        if (res.code === 200) {
          let durationLimitation = res.data>=5&&res.data<10
          console.log("时长是否在范围内",durationLimitation)
          if (!durationLimitation){
            that.url=""
            that.$u.toast("上传失败录音时长不能小于5秒大于10秒");
            return
          } else {
            that.url = url
            that.$u.toast("上传成功")
          }

        }
      }
		}
	}
</script>

<style lang="less" scoped>
	/deep/ .uni-audio-default {
		width: 628rpx;
		min-width: 400rpx;
		height: 88rpx;
		margin-top: 10rpx;
	}
	/deep/ .uni-audio-left {
		width: 88rpx;
		height: 88rpx;
	}
	/deep/ .uni-audio-right {
		margin-left: 0;
		height: 88rpx;
	}
	/deep/ .uni-audio-button {
		width: 40rpx;
		height: 40rpx;
		margin: 24rpx
	}
	.main-content {
		width: 100%;
		height: calc(100vh - var(--window-bottom) - var(--window-top) - 92rpx);
		padding: 30rpx;
		box-sizing: border-box;
		background: linear-gradient(to bottom, #10B981, #3B82F6);
		.content {
			width: 100%;
			height: 100%;
			background: #fff;
			border-radius: 12rpx;
			padding: 30rpx;
			box-sizing: border-box;
			.h2 {
				font-weight: 700 ;
				font-size: 30rpx;
				color: #000;
				padding: 40rpx 0 15rpx 0;
			}
			.tip {
				font-size: 26rpx;
			}
			.uploadBtn {
				width: 100%;
				height: 88rpx;
				background: linear-gradient(to bottom, #10B981, #3B82F6);
				border-radius: 12rpx;
				color: #fff;
				text-align: center;
				line-height: 88rpx;
			}
			.inpVue {
				width: 100%;
				.label {
					font-weight: 600;
					font-size: 28rpx;
				}
				.sudioVue {
					width: 100%;
					height: 88rpx;
					border-radius: 10rpx;
					margin-top: 12rpx;
					text {
						color: #333;
						line-height: 50rpx;
						padding-left: 15rpx;
					}
				}
				input {
					width: 100%;
					height: 88rpx;
					border: 1rpx solid #EBEDED;
					border-radius: 10rpx;
					display: block;
					margin-top: 12rpx;
					padding-left: 20rpx;
					font-size: 28rpx;
				}
				.radioVue {
					width: 690rpx;
					.radio {
						height: 80rpx;
						margin-right: 40rpx;
					}
				}
			}
			.startBtn {
				width: 100%;
				height: 88rpx;
				background: linear-gradient(to right, #10B981, #3B82F6);
				border-radius: 12rpx;
				line-height: 88rpx;
				text-align: center;
				color: #fff;
			}
			.tabItem {
				width: 100%;
				height: 88rpx;
				margin-bottom: 15rpx;
			}
			.tabActive {
			  background: #3B82F6;
			}
			.progressItem {
				width: 100%;
				height: 88rpx;
				margin-top: 30rpx;
				border: 1rpx solid #e0e0e0;
				padding: 0 20rpx;
				border-radius: 12rpx;
				.name {
					width: 200rpx;
					height: 80rpx;
					line-height: 80rpx;
					font-size: 26rpx;
					font-weight: 500;
					margin-right: 20rpx;
					color: #3B82F6;
				}
			}
		}
	}
</style>
